'use client';

import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer } from 'recharts';
import { useQuery } from '@tanstack/react-query';
import { multiChainApi } from '@/lib/multi-chain-api';
import { useChain } from '@/context/ChainContext';

interface ChartData {
  name: string;
  date: string;
  pos: number;
  pop: number;
}

interface NetworkActivityResponse {
  data: ChartData[];
  period: string;
  total_pos: number;
  total_pop: number;
}

export function StatsChart() {
  const { currentChain } = useChain();
  
  const { data: chartData, isLoading } = useQuery<NetworkActivityResponse>({
    queryKey: ['network-activity-chart', currentChain],
    queryFn: async () => {
      const client = multiChainApi.getClient(currentChain);
      const response = await client.get('/api/v1/admin/charts/network-activity');
      return response.data;
    },
    refetchInterval: 300000, // Refresh every 5 minutes
  });

  // Default data while loading or on error (daily increments)
  const defaultData: ChartData[] = [
    { name: 'Mon', date: '2024-01-01', pos: 1200, pop: 85 },
    { name: 'Tue', date: '2024-01-02', pos: 500, pop: 20 },
    { name: 'Wed', date: '2024-01-03', pos: 300, pop: 20 },
    { name: 'Thu', date: '2024-01-04', pos: 400, pop: 60 },
    { name: 'Fri', date: '2024-01-05', pos: 600, pop: 100 },
    { name: 'Sat', date: '2024-01-06', pos: 300, pop: 100 },
    { name: 'Sun', date: '2024-01-07', pos: 161, pop: 88 },
  ];

  const data = chartData?.data || defaultData;

  return (
    <div className="h-80">
      <ResponsiveContainer width="100%" height="100%">
        <LineChart data={data} margin={{ top: 5, right: 30, left: 20, bottom: 5 }}>
          <CartesianGrid strokeDasharray="3 3" stroke="#f0f0f0" />
          <XAxis dataKey="name" stroke="#888" />
          <YAxis stroke="#888" />
          <Tooltip 
            contentStyle={{ 
              backgroundColor: '#fff', 
              border: '1px solid #e0e0e0',
              borderRadius: '8px'
            }}
          />
          <Line 
            type="monotone" 
            dataKey="pos" 
            stroke="#3b82f6" 
            strokeWidth={2}
            dot={{ fill: '#3b82f6', r: 4 }}
            name="每日新增POS"
          />
          <Line 
            type="monotone" 
            dataKey="pop" 
            stroke="#10b981" 
            strokeWidth={2}
            dot={{ fill: '#10b981', r: 4 }}
            name="每日新增POP"
          />
        </LineChart>
      </ResponsiveContainer>
      {isLoading && (
        <div className="absolute inset-0 flex items-center justify-center bg-white bg-opacity-75">
          <div className="text-sm text-gray-500">Loading chart data...</div>
        </div>
      )}
    </div>
  );
}